package com.leemz.algorithm.binarysearch;

/**
 * Created by leemz on 2017/4/25.
 * 实现二分查询算法
 */
public class BinarySearchTest {
    public static void main(String[] args) {
        int[] guess = {11, 18, 29, 37, 42, 49, 51, 63, 69, 72, 77, 82, 88, 91, 98};
        int target = 77;
        int index = binarySearch(guess, target);
        System.out.println(index);
    }

    public static int binarySearch(int[] guess, int target) {
        int low = 0;
        int high = guess.length - 1;
        while (low <= high) {
            int middle = (low + high) / 2;
            if(guess[middle] == target) {
                return middle;
            } else if(guess[middle] > target) {
                high = middle - 1;
            } else {
                low = middle + 1;
            }
        }
        return -1;
    }
}
